import React, { useState, useEffect } from 'react';
import { View, Text, Image, FlatList, TouchableOpacity, TextInput, Modal, RefreshControl, ActivityIndicator, Alert } from 'react-native';
import { Stack, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../context/ThemeContext';
import { getFollowings, toggleFollowUser, checkIsFollowing } from '../services/userService';
import defaultAvatarImage from '../../assets/default_avatar.png';
import { StatusBar } from 'expo-status-bar';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

// 定义关注用户数据类型
interface Following {
  userId: number;
  studentId: string;
  userName: string;
  userAvatar: string;
  userProfile: string;
  gender: string;
  college: string;
  major: string;
  followTime: string;
  isFollowedBack: boolean;
  grade?: string;
}

// 定义API返回的关注用户数据类型
interface ApiFollowing {
  userId: number;
  studentId: string;
  userName: string;
  userAvatar: string;
  userProfile: string;
  gender: string;
  college: string;
  major: string;
  followTime: string;
  grade?: string;
}

export default function FollowingsScreen() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets(); // 获取设备安全区域尺寸
  const [followings, setFollowings] = useState<Following[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [modalMessage, setModalMessage] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const [avatarErrors, setAvatarErrors] = useState<{[key: number]: boolean}>({});
  const [followLoading, setFollowLoading] = useState<{[key: number]: boolean}>({});
  const pageSize = 10;
  
  // 获取关注列表
  const fetchFollowings = async (page = 1, showLoading = true) => {
    if (showLoading) {
      setLoading(true);
    }
    
    try {
      const response = await getFollowings({
        current: page,
        pageSize
      });
      
      if (response && response.data) {
        let newFollowings = response.data.records || [] as ApiFollowing[];
        
        if (page === 1) {
          setFollowings(newFollowings);
        } else {
          setFollowings(prev => [...prev, ...newFollowings]);
        }
        
        setTotal(response.data.total || 0);
        setCurrentPage(page);
        setHasMore((response.data.records || []).length === pageSize);
      }
    } catch (error: any) {
      console.error('获取关注列表失败:', error.message);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };
  
  // 组件初次渲染时获取数据
  useEffect(() => {
    fetchFollowings();
  }, []);
  
  // 下拉刷新
  const handleRefresh = () => {
    setRefreshing(true);
    fetchFollowings(1, false);
  };
  
  // 加载更多数据
  const handleLoadMore = () => {
    if (!loading && hasMore) {
      fetchFollowings(currentPage + 1);
    }
  };
  
  // 处理取消关注按钮点击
  const handleFollowToggle = async (userId: number) => {
    // 防止重复点击
    if (followLoading[userId]) return;
    
    // 设置指定用户的关注状态为加载中
    setFollowLoading(prev => ({
      ...prev,
      [userId]: true
    }));
    
    try {
      // 调用关注/取消关注接口
      const response = await toggleFollowUser(userId);
      
      if (response && response.data !== undefined) {
        // 从列表中移除该用户（因为取消关注后应从关注列表中移除）
        setFollowings(followings.filter(following => following.userId !== userId));
        
        // 显示操作成功提示
        Alert.alert("取消关注成功", "已取消关注该用户");
      }
    } catch (error: any) {
      console.error('取消关注操作失败:', error.message);
      Alert.alert('操作失败', error.response?.data?.message || '请稍后重试');
    } finally {
      // 清除加载状态
      setFollowLoading(prev => ({
        ...prev,
        [userId]: false
      }));
    }
  };
  
  // 处理搜索按钮点击
  const handleSearch = () => {
    if (!searchText.trim()) {
      // 如果搜索框为空，刷新列表
      handleRefresh();
      return;
    }
    
    // 根据输入内容过滤关注列表（本地过滤）
    const filteredFollowings = followings.filter(following => 
      following.userName.includes(searchText) || 
      following.studentId.includes(searchText) ||
      (following.college && following.college.includes(searchText)) ||
      (following.major && following.major.includes(searchText))
    );
    
    if (filteredFollowings.length === 0) {
      Alert.alert('提示', '没有找到匹配的关注用户');
    } else {
      setFollowings(filteredFollowings);
    }
  };
  
  // 处理头像加载错误
  const handleAvatarError = (userId: number) => {
    setAvatarErrors(prev => ({
      ...prev,
      [userId]: true
    }));
  };
  
  // 渲染关注列表项
  const renderFollowingItem = ({ item }: { item: Following }) => {
    // 默认头像URL
    const defaultAvatar = Image.resolveAssetSource(defaultAvatarImage).uri;
    const isLoading = followLoading[item.userId] || false;
    
    return (
      <View className={`flex-row items-center py-3 border-b ${isDarkMode ? 'border-zinc-800' : 'border-gray-100'}`}>
        <Image 
          source={{ 
            uri: avatarErrors[item.userId] 
              ? defaultAvatar 
              : (item.userAvatar || defaultAvatar) 
          }}
          className="w-12 h-12 rounded-full"
          defaultSource={defaultAvatarImage}
          onError={() => handleAvatarError(item.userId)}
        />
        
        <View className="flex-1 ml-3">
          <Text className={`text-base font-medium mb-1 ${isDarkMode ? 'text-white' : 'text-gray-800'}`}>
            {item.userName}
          </Text>
          <Text className={`text-xs ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
            {item.major || '未设置专业'} • {item.grade || item.college || '未设置年级'}
          </Text>
        </View>
        
        <TouchableOpacity 
          className={`px-4 py-1.5 rounded-full ${
            isLoading 
              ? 'bg-gray-300' 
              : (item.isFollowedBack 
                ? 'bg-transparent border border-gray-300' 
                : 'bg-blue-500')
          }`}
          onPress={() => handleFollowToggle(item.userId)}
          disabled={isLoading}
        >
          {isLoading ? (
            <ActivityIndicator size="small" color={isDarkMode ? "#fff" : "#666"} />
          ) : (
            <Text className={`text-sm font-medium ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
              已关注
            </Text>
          )}
        </TouchableOpacity>
      </View>
    );
  };
  
  // 渲染列表底部加载状态
  const renderFooter = () => {
    if (!hasMore) return (
      <Text className={`text-center py-4 text-sm ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
        {followings.length > 0 ? '已加载全部数据' : '暂无关注的用户'}
      </Text>
    );
    
    if (loading && currentPage > 1) return (
      <View className="flex-row justify-center items-center py-4">
        <ActivityIndicator color="#1677FF" />
        <Text className={`ml-2 text-sm ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
          加载中...
        </Text>
      </View>
    );
    
    return null;
  };
  
  return (
    <View className={`flex-1 ${isDarkMode ? 'bg-gray-900' : 'bg-gray-100'}`}>
      <StatusBar style={isDarkMode ? 'light' : 'dark'} />
      
      {/* 自定义头部导航 - 添加状态栏高度的paddingTop */}
      <View 
        className="bg-blue-500 w-full"
        style={{ paddingTop: insets.top }}
      >
        <View className="flex-row items-center justify-center h-14 relative">
          <TouchableOpacity 
            className="absolute left-4 z-10"
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color="#FFFFFF" />
          </TouchableOpacity>
          
          <Text className="text-white text-lg font-medium">我的关注</Text>
        </View>
      </View>
      
      {/* 搜索框 */}
      <View className="px-4 py-3">
        <View className={`flex-row items-center rounded-md shadow-sm overflow-hidden ${
          isDarkMode ? 'bg-zinc-800' : 'bg-white'
        }`}>
          <View className="flex-row items-center flex-1 px-3">
            <Ionicons 
              name="search-outline" 
              size={20} 
              color={isDarkMode ? '#AAAAAA' : '#999999'} 
            />
            <TextInput
              className={`flex-1 ml-2 py-2.5 text-base ${isDarkMode ? 'text-white' : 'text-gray-800'}`}
              placeholder="搜索关注的用户"
              placeholderTextColor={isDarkMode ? '#AAAAAA' : '#999999'}
              value={searchText}
              onChangeText={setSearchText}
              returnKeyType="search"
              onSubmitEditing={handleSearch}
            />
          </View>
          
          <TouchableOpacity 
            className="bg-blue-500 px-5 py-2.5 items-center justify-center"
            onPress={handleSearch}
          >
            <Text className="text-white font-medium">搜索</Text>
          </TouchableOpacity>
        </View>
      </View>
      
      {/* 关注列表 */}
      {loading && currentPage === 1 ? (
        <View className="flex-1 justify-center items-center">
          <ActivityIndicator color="#1677FF" size="large" />
          <Text className={`mt-3 text-sm ${isDarkMode ? 'text-white' : 'text-gray-600'}`}>
            加载中...
          </Text>
        </View>
      ) : (
        <FlatList
          data={followings}
          renderItem={renderFollowingItem}
          keyExtractor={item => item.userId.toString()}
          contentContainerStyle={{ paddingHorizontal: 16 }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={handleRefresh}
              colors={['#1677FF']}
              tintColor={isDarkMode ? '#5DADE2' : '#1677FF'}
              title="刷新中..."
              titleColor={isDarkMode ? '#AAAAAA' : '#999999'}
            />
          }
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.2}
          ListFooterComponent={renderFooter}
          ListEmptyComponent={!loading ? (
            <Text className={`text-center mt-10 text-base ${isDarkMode ? 'text-white' : 'text-gray-600'}`}>
              暂无关注的用户
            </Text>
          ) : null}
        />
      )}
      
      {/* 功能开发中弹窗 */}
      <Modal
        animationType="fade"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => setModalVisible(false)}
      >
        <View className="flex-1 bg-black/50 justify-center items-center">
          <View className={`w-4/5 rounded-xl p-6 items-center ${isDarkMode ? 'bg-zinc-800' : 'bg-white'}`}>
            <Text className={`text-base text-center mb-5 ${isDarkMode ? 'text-white' : 'text-gray-800'}`}>
              {modalMessage}
            </Text>
            <TouchableOpacity 
              className="bg-blue-500 py-2.5 px-6 rounded-lg"
              onPress={() => setModalVisible(false)}
            >
              <Text className="text-white text-base font-medium">我知道了</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
} 